package com.biboheart.brick.utils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

public class JsonUtils {
	private static JsonFactory jf = null;
	private static ObjectMapper mapper = null;

	/**
	 * 获取com.fasterxml.jackson.databind.ObjectMapper对象实例，如果实例不存在则创建
	 * @return com.fasterxml.jackson.databind.ObjectMapper对象实例
	 */
	private static ObjectMapper getMapper() {
		if (mapper == null) {
			mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		}
		return mapper;
	}

	/**
	 * 获取com.fasterxml.jackson.core.JsonFactory对象实例，如果实例不存在则创建
	 * @return com.fasterxml.jackson.core.JsonFactory对象实例
	 */
	private static JsonFactory getFactory() {
		if (jf == null)
			jf = new JsonFactory();
		return jf;
	}

	/**
	 * 对象转json字符串
	 * @param obj 要转换的对象
	 * @return json字符串
	 */
	public static String obj2json(Object obj) {
		if(null == obj) {
			return null;
		}
		JsonGenerator jg = null;
		try {
			jf = getFactory();
			mapper = getMapper();
			StringWriter out = new StringWriter();
			jg = jf.createGenerator(out);
			mapper.writeValue(jg, obj);
			return out.toString();
		} catch (IOException ignore) {
		} finally {
			try {
				if (jg != null)
					jg.close();
			} catch (IOException ignore) {
			}
		}
		return null;
	}

	/**
	 * json字符串转对象
	 * @param json json字符串
	 * @param clz 匹配的对象类
	 * @return 转换的对象，如果转换失败返回null
	 */
	public static Object json2obj(String json, Class<?> clz) {
		if(null == json || json.isEmpty()){
			return null;
		}
		try {
			mapper = getMapper();
			return mapper.readValue(json, clz);
		} catch (IOException ignore) {
		}
		return null;
	}

	/**
	 * json字符串转对象
	 * @param json json字符串
	 * @param clz 匹配的对象类
	 * @param <T> 指定转换后的类型
	 * @return 转换的对象，确定转换类型，如果转换失败返回null
	 */
	public static <T> T json2objWithType(String json, Class<T> clz) {
		if(null == json || json.isEmpty()){
			return null;
		}
		try {
			mapper = getMapper();
			return mapper.readValue(json, clz);
		} catch (IOException ignore) {
		}
		return null;
	}
}
